﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.MultiTenancy.ConfigurationStore;
using Xms.Abp.Modularity;

namespace Xms.Abp.MultiTenancy;

[DependsOn(typeof(AbpMultiTenancyModule))]
public class XmsAbpMultiTenancyModule : XmsModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        base.ConfigureServices(context);

        var configuration = context.Services.GetConfiguration();
        Configure<XmsDefaultTenantStoreOptions>(configuration);
    }

    public override void PostConfigureServices(ServiceConfigurationContext context)
    {
        base.PostConfigureServices(context);
        var services = context.Services.Where(r => r.ServiceType == typeof(ITenantStore));
        var remove = services.FirstOrDefault(r => r.ImplementationType == typeof(DefaultTenantStore));
        if (remove != null)
        {
            context.Services.Remove(remove);
        }
        if (!context.Services.Any(r => r.ServiceType == typeof(ITenantStore)))
        {
            context.Services.AddTransient<ITenantStore, DefaultMultiTenantStore>();
        }

        var sp = context.Services.BuildServiceProvider();
        var xmsOptions = sp.GetRequiredService<IOptions<XmsDefaultTenantStoreOptions>>().Value;
        PostConfigure<AbpDefaultTenantStoreOptions>(options =>
        {
            options.Tenants = xmsOptions.Tenants;
        });
    }
}
